package com.kgc.ssm.controller;

import com.kgc.ssm.entity.SysUsers;
import com.kgc.ssm.service.SysUsersService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

//用户控制器
@Controller
@RequestMapping("/sysUsers")
public class SysUsersController {
    @Autowired
    private SysUsersService sysUsersService;

    //登录处理
    @PostMapping("/login")
    public String login(String loginId, String password, @RequestParam(value = "rememberMe", defaultValue = "false") boolean rememberMe) {
        Subject subject = SecurityUtils.getSubject();
        try {
            // 将 rememberMe 参数传递给令牌
            UsernamePasswordToken token = new UsernamePasswordToken(loginId, password, rememberMe);
            subject.login(token);
            // 认证成功，进入主页
            return "redirect:/index.html";
        } catch (UnknownAccountException ex) {
            ex.printStackTrace();
            System.out.println("用户名不存在");
        } catch (IncorrectCredentialsException ex) {
            ex.printStackTrace();
            System.out.println("密码错误");
        }
        // 认证失败，回到登录页面
        return "login";
    }

    //注销
    @GetMapping("/logout")
    public String logout(){
        SecurityUtils.getSubject().logout();
        // 跳转登录页面
        return "login";
    }

    //处理注册
    @PostMapping("/register")
    public String register(SysUsers sysUsers){
        //调用业务层的注册方法
        try {
            sysUsers.setStatus("1");
            sysUsersService.register(sysUsers);
            System.out.println("注册成功");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("注册失败");
            //注册失败，回到注册页面
            return "register";
        }
        //注册成功，跳转登录页面
        return "login";
    }
}